package com.tql.pandian.service.impl;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.constant.CommonUtil;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteKingdeeService;
import com.ruoyi.system.api.domain.EmpResponse;
import com.ruoyi.system.api.domain.SysFile;
import com.ruoyi.system.api.domain.SysUser;

import com.tql.pandian.entity.TqlEmpEntity;
import com.tql.pandian.entity.sys.SysMenuEntity;
import com.tql.pandian.entity.sys.SysRoleEntity;
import com.tql.pandian.entity.sys.SysUserEntity;
import com.tql.pandian.entity.sys.dto.*;
import com.tql.pandian.entity.sys.vo.SysMenuVo;
import com.tql.pandian.entity.sys.vo.SysRoleMenuVo;
import com.tql.pandian.entity.sys.vo.SysUserVo;
import com.tql.pandian.entity.vo.DepotPostVo;
import com.tql.pandian.mapper.CommonMapper;
import com.tql.pandian.mapper.TqlEmpMapper;
import com.tql.pandian.mapper.TqlPandianCaseMapper;
import com.tql.pandian.mapper.UserRoleMenuMapper;
import com.tql.pandian.service.IH5RoleMenuService;
import com.tql.pandian.util.ConvertUtils;
import com.tql.pandian.util.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class H5RoleMenuService implements IH5RoleMenuService {

    @Autowired
    private RemoteKingdeeService remoteKingdeeService;

    @Autowired
    private UserRoleMenuMapper userRoleMenuMapper;

    @Autowired
    private TqlEmpMapper tqlEmpMapper;

    @Autowired
    private CommonMapper commonMapper;

    @Autowired
    private TqlPandianCaseMapper tqlPandianCaseMapper;




    @Override
    public int addMenu(SysMenuDTO sysMenuDTO) {
        SysMenuEntity sysMenuEntity = new SysMenuEntity();
        sysMenuEntity.setMenuName(sysMenuDTO.getMenuName());
        sysMenuEntity.setParentId(sysMenuDTO.getParentId());
        sysMenuEntity.setOrderNum(sysMenuDTO.getOrderNum());
        sysMenuEntity.setPath(sysMenuDTO.getPath());
        sysMenuEntity.setComponent(sysMenuDTO.getComponent());
        sysMenuEntity.setIsFrame(3);
        sysMenuEntity.setIsCache(0);
        sysMenuEntity.setMenuType(sysMenuDTO.getMenuType());
        sysMenuEntity.setVisible(sysMenuDTO.getVisible());
        sysMenuEntity.setStatus(0);
        sysMenuEntity.setPerms(sysMenuDTO.getPerms());
        sysMenuEntity.setIcon(sysMenuDTO.getIcon());
        sysMenuEntity.setCreateBy(SecurityUtils.getUsername());
        sysMenuEntity.setCreateTime(new Date());
        sysMenuEntity.setRemark(sysMenuDTO.getRemark());
        return userRoleMenuMapper.insertMenu(sysMenuEntity);
    }

    @Override
    public List<SysMenuVo> getMenu() {
        return userRoleMenuMapper.selectMenuList();
    }

    @Override
    public int addRole(SysRoleDTO sysRoleDTO) {
        int a = 0;
        //插入角色表
        SysRoleEntity sysRoleEntity = new SysRoleEntity();
        sysRoleEntity.setRoleName(sysRoleDTO.getRoleName());
        sysRoleEntity.setRoleKey(sysRoleEntity.getRoleKey());
        sysRoleEntity.setRoleSort(sysRoleDTO.getRoleSort());
        sysRoleEntity.setDataScope(4);
        sysRoleEntity.setMenuCheckStrictly(1);
        sysRoleEntity.setDeptCheckStrictly(1);
        sysRoleEntity.setStatus(0);
        sysRoleEntity.setDelFlag(0);
        sysRoleEntity.setCreateBy(SecurityUtils.getUsername());
        sysRoleEntity.setCreateTime(new Date());
        sysRoleEntity.setRemark(sysRoleDTO.getRemark());
        sysRoleEntity.setFlag(1);
        a = userRoleMenuMapper.insertRole(sysRoleEntity);
        //插入角色绑定菜单表
        List<SysRoleMenuDTO> sysRoleMenuList = new ArrayList<>();
        sysRoleDTO.getMenuIds().forEach(t->{
            SysRoleMenuDTO sysRoleMenuDTO = new SysRoleMenuDTO();
            sysRoleMenuDTO.setMenuId(t);
            sysRoleMenuDTO.setRoleId(sysRoleEntity.getRoleId());
            sysRoleMenuList.add(sysRoleMenuDTO);
        });
        int b = userRoleMenuMapper.batchRoleMenu(sysRoleMenuList);
        return a+b;
    }

    @Override
    public List<Map> getRoleList() {
        boolean flag= SecurityUtils.isAdmin(SecurityUtils.getUserId());
        //超级管理员(能看所有的权限)
        if(flag){
            return userRoleMenuMapper.selectRoleList();
        }else {
            return userRoleMenuMapper.selectRoleListByUser(SecurityUtils.getUserId());
        }
    }

    @Override
    public SysRoleMenuVo getRole(Long roleId) {
        return userRoleMenuMapper.selectSysRoleByRoleId(roleId);
    }

    @Override
    public int updateRole(SysRoleDTO sysRoleDTO) {
        SysRoleEntity sysRoleEntity = new SysRoleEntity();
        sysRoleEntity.setRoleName(sysRoleDTO.getRoleName());
        sysRoleEntity.setRoleKey(sysRoleEntity.getRoleKey());
        sysRoleEntity.setRoleSort(sysRoleDTO.getRoleSort());
        sysRoleEntity.setRemark(sysRoleDTO.getRemark());
        sysRoleEntity.setUpdateBy(SecurityUtils.getUsername());
        sysRoleEntity.setUpdateTime(new Date());
        int a = userRoleMenuMapper.updateRole(sysRoleEntity);

        //删除角色绑定菜单
        int b = userRoleMenuMapper.deleteRoleMenu(sysRoleDTO.getRoleId());
        //再插入角色绑定菜单表
        List<SysRoleMenuDTO> sysRoleMenuList = new ArrayList<>();
        sysRoleDTO.getMenuIds().forEach(t->{
            SysRoleMenuDTO sysRoleMenuDTO = new SysRoleMenuDTO();
            sysRoleMenuDTO.setMenuId(t);
            sysRoleMenuDTO.setRoleId(sysRoleEntity.getRoleId());
            sysRoleMenuList.add(sysRoleMenuDTO);
        });
        int c = userRoleMenuMapper.batchRoleMenu(sysRoleMenuList);
        return c;
    }

    @Override
    public int deleteRole(Long roleId) {
        //删除角色表
        int a = userRoleMenuMapper.deleteRole(roleId);
        //删除角色绑定菜单表
        int b = userRoleMenuMapper.deleteRoleMenu(roleId);
        return a+b;
    }

    @Override
    public List<Map> getAppUser() {
        //门店编码
        String deptCode = SecurityUtils.getLoginUser().getSysUser().getDeptCode();
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        boolean flag= SecurityUtils.isAdmin(SecurityUtils.getUserId());
        //超级管理员
        if(flag){
            return tqlPandianCaseMapper.selectAllAppUser();
        }
        /*if (StringUtils.isNotEmpty(deptCode)){
            List<Map> maps = commonMapper.selectDeptCollection(deptCode);
            if (maps.size() > 0){
                List<Long> deptIds = maps.stream().map(t->(Long) t.get("dept_id")).collect(Collectors.toList());
                return tqlPandianCaseMapper.selectPanDianPerson(deptIds).stream().filter(k->!k.get("user_id").equals(SecurityUtils.getUserId())).collect(Collectors.toList());
            }
        }*/
        return tqlPandianCaseMapper.selectStageMan(deptCode);
    }

    @Override
    public int addAppUser(SysUserDTO sysUserDTO) {
        int a = 0;
         //用户登录表
        SysUserEntity sysUserEntity = new SysUserEntity();
        sysUserEntity.setDeptId(sysUserDTO.getDeptId());
        sysUserEntity.setUserName(sysUserDTO.getFMobile()); //登录账号为手机号码
        //sysUserEntity.setUserName(PinYinUtil.getPinyin(sysUserDTO.getUserName()));
        sysUserEntity.setNickName(sysUserDTO.getUserName());
        sysUserEntity.setUserType("00");
        sysUserEntity.setEmail(sysUserDTO.getEmail());
        sysUserEntity.setPhonenumber(sysUserDTO.getFMobile());
        sysUserEntity.setSex(sysUserDTO.getSex());
        sysUserEntity.setAvatar(sysUserDTO.getAvatar());
        sysUserEntity.setPassword(SecurityUtils.encryptPassword(CommonUtil.H5UserPassword));
        sysUserEntity.setStatus(0);
        sysUserEntity.setDelFlag(0);
        sysUserEntity.setCreateBy(SecurityUtils.getUsername());
        sysUserEntity.setCreateTime(new Date());
        sysUserEntity.setRemark("移动端登录账号");
        sysUserEntity.setFlag(1);
        a = userRoleMenuMapper.insertUser(sysUserEntity);
        //用户绑定角色
        List<SysUserRoleDTO> userRoleList = new ArrayList<>();
        sysUserDTO.getRoleIds().forEach(k->{
            SysUserRoleDTO sysUserRoleDTO = new SysUserRoleDTO();
            sysUserRoleDTO.setRoleId(k);
            sysUserRoleDTO.setUserId(sysUserEntity.getUserId());
            userRoleList.add(sysUserRoleDTO);
        });
        int b =  userRoleMenuMapper.batchUserRole(userRoleList);
        return a+b;
    }

    @Override
    public SysUserVo getAppUserByUserId(Long userId) {
        return userRoleMenuMapper.selectAppUserByUserId(userId);
    }

    @Override
    public int editAppUser(SysUserDTO sysUserDTO) {
        //删除用户绑定角色表
        int a = userRoleMenuMapper.deleteUserRole(sysUserDTO.getUserId());

        //再插入用户绑定角色表
        List<SysUserRoleDTO> list = new ArrayList<>();
        sysUserDTO.getRoleIds().forEach(l->{
            SysUserRoleDTO sysUserRoleDTO = new SysUserRoleDTO();
            sysUserRoleDTO.setUserId(sysUserDTO.getUserId());
            sysUserRoleDTO.setRoleId(l);
            list.add(sysUserRoleDTO);
        });
        int c = userRoleMenuMapper.batchUserRole(list);
        return c;
    }

    /**
     * 删除用户
     * @param userId
     * @return
     */
    @Override
    public int deleteAppUserByUserId(Long userId) {
        //删除角色绑定用户
        int a = userRoleMenuMapper.deleteUserRole(userId);
        //删除用户表
        int b = userRoleMenuMapper.deleteUserByUserId(userId);
        return a+b;
    }


    @Override
    public List<EmpResponse> selectUser(String idcard) {

                PageInfo pageInfo =null;
                List<TqlEmpEntity> list0=tqlEmpMapper.selectEmpList(idcard);

                if(!CollectionUtils.isEmpty(list0))
                {
                    List<EmpResponse> list1 = list0.stream()
                            .map(each -> {
                                EmpResponse empResponse = new EmpResponse();
                                empResponse.setF_WGNV_Text(each.getF_WGNV_Text());
                                empResponse.setFID(each.getFID());
                                empResponse.setFname(each.getFname());
                                empResponse.setFMobile(each.getFMobile());
                                empResponse.setFNumber(each.getFNumber());
                                empResponse.setFStaffNumber(each.getFStaffNumber());
                                empResponse.setFUseOrgIdfname(each.getFUseOrgIdfname());
                                empResponse.setFUseOrgIdfnumber(each.getFUseOrgIdfnumber());
                                // 在这里将tqlEmpEntity的属性值复制到empResponse的属性中
                                return empResponse;
                            })
                            .collect(Collectors.toList());
                            return list1;


                }
                else {
                    R<List<EmpResponse>> fileResult = remoteKingdeeService.getEmpByIdCard(idcard);
                    if (StringUtils.isNull(fileResult) || StringUtils.isNull(fileResult.getData())) {
                        throw new ServiceException("未找到相关人员");
                    }
                    return fileResult.getData();
                }
    }

    @Override
    public List<TreeNode> getStoreTree() {
        SysUser sysUser =SecurityUtils.getLoginUser().getSysUser();
        String deptCode = SecurityUtils.getLoginUser().getSysUser().getDeptCode();
        boolean flag= SecurityUtils.isAdmin(SecurityUtils.getUserId());
        List<Map> maps;
        if (flag){
            maps = commonMapper.selectDeptAdminCollection();
        }else {
            maps = commonMapper.selectDeptCollection(deptCode);
        }
        List<DepotPostVo> depotPostVoList = maps.stream().map(t->{
            DepotPostVo depotPostVo = new DepotPostVo();
            depotPostVo.setDeptId((Long) t.get("dept_id"));
            depotPostVo.setParentId((Long) t.get("parent_id"));
            depotPostVo.setDeptName((String) t.get("dept_name"));
            depotPostVo.setDeptCode((String) t.get("dept_code"));
            return depotPostVo;
        }).collect(Collectors.toList());
        List<TreeNode> voList = ConvertUtils.sourceToTarget(depotPostVoList, TreeNode.class);
        return voList;
        //return TreeUtils.build(voList);
    }
}
